#include "data.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

#include "global.h"


// Directory of the data (images, fonts, etc) and config (personal files).
static char *datadir, configdir[255];

// Variables used for building the datapath and configpath.
static char databuffer[255], configbuffer[255];


// Executed when the user runs the game for the first time.
void first_run()
{
	// TODO
	cm_mkdir(configpath(""), 0744);
}


// Initialize data information.
void data_init()
{
	struct stat buffer;
	int error;

	// Find data directory - look for error.ttf
	error = stat(DATADIR "/error.ttf", &buffer);
	if(error)
	{
		error = stat("./data/error.ttf", &buffer);
		if(error)
		{
			error = stat("./src/data/error.ttf", &buffer);
			if(error)
			{
				fprintf(stderr, _("Data directory not found.\n"));
				exit(2);
			}
			else
				datadir = "./src/data";
		}
		else
			datadir = "./data";
	}
	else
		datadir = DATADIR;

	// Find config directory
#ifdef _WIN32
	sprintf(configdir, "%s\\citymanager", getenv("APPDATA"));
	// TODO - mark dir as hidden
#else
	sprintf(configdir, "%s/.citymanager", getenv("HOME"));
#endif

	// check for first run
	error = stat(configdir, &buffer);
	if(error)
	{
		if(errno == ENOENT)
			first_run();
		else
		{
			fprintf(stderr, _("Error creating or accessing config directory.\n"));
			exit(2);
		}
	}
}


// Return full path for a data file. String doesn not need to be freed as
// it'll be reused every time.
char* datapath(char* filename)
{
	sprintf(databuffer, "%s/%s", datadir, filename);
	return databuffer;
}


// Return full path for a data file. String doesn not need to be freed as
// it'll be reused every time.
char* configpath(char* filename)
{
	sprintf(configbuffer, "%s/%s", configdir, filename);
	return configbuffer;
}


// Convert a given string to a filename, removing all invalid chars.
static char cvt[256];
char* convert_to_filename(char* string)
{
	int i=0, j=0;
	for(i=0; i<strlen(string); i++)
		if(isalnum(string[i]))
			cvt[j++] = tolower(string[i]);
		else
			cvt[j++] = '_'; // TODO - intl chars
	cvt[j++] = 0;
	return cvt;
}
